'use strict';
//define(['angular','common','attachments','angularSummernote'], function(angular,common) {
//	angular.module('backcenter.ognSingle', ['app.attachments','summernote'])

define(['angular'], function(angular) {
	angular.module('backcenter.ognSingle', [])

	.controller('ognSingleCtrl'
			,['$rootScope', '$scope', 'BizData','$stateParams', '$state'
	        , '$uibModal', '$ocLazyLoad', f]);

	                               
    function f($rootScope, $scope, BizData, $stateParams, $state, $uibModal, $ocLazyLoad) {
		var common = require('common');
		
		var Model = this;

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataOrgBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataOrgAfterDelete = function(event) {
//			alert('删除之后！')
		}


		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataOrgIndexChanged = function(event) {
			
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataOrgDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataOrgValueChanged = function(event) {
			
			if(event.column=='sCode'){
				//整合自身全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sCode = event.value;
				var sFCode = '';
				if(sParent==null){
					sFCode = sFCode + '/' + sCode;
				}else{
					sFCode = event.source.getValue('sFCode',sParent) + '/' + sCode;
				}
				event.source.setValue('sFCode',sFCode,rowID);
			}
			if(event.column=='sFCode'){
				//修改子节点的全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFCode = event.value + '/' + event.source.getValue('sCode',ids[i]);
					event.source.setValue('sFCode',sFCode,ids[i]);
				}
			}
			if(event.column=='sName'){
				//整合自身全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sName = event.value;
				var sFName = '';
				if(sParent==null){
					sFName = sFName + '/' + sName;
				}else{
					sFName = event.source.getValue('sFName',sParent) + '/' + sName;
				}
				event.source.setValue('sFName',sFName,rowID);
			}
			if(event.column=='sFName'){
				//修改子节点的全路径名称
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFName = event.value + '/' + event.source.getValue('sName',ids[i]);
					event.source.setValue('sFName',sFName,ids[i]);
				}
			}

			
			if(event.column=='sID'){
				//整合自身全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var sParent = event.source.getValue('sParent',rowID);
				var sOrgKindID = event.source.getValue('sOrgKindID',rowID);
				var sID = event.value;
				var sFID = '';
				if(sParent==null){
					sFID = sFID + '/' + sID + '.' + sOrgKindID;
				}else{
					sFID = event.source.getValue('sFID',sParent) + '/' + sID + '.' + sOrgKindID;
				}
				event.source.setValue('sFID',sFID,rowID);
			}
			if(event.column=='sFID'){
				//修改子节点的全路径编码
				var rowID = event.source.getID(event.rowIndex);
				var ids = $scope.dataOrg.getChildsIDs(rowID);
				for(var i=0;i<ids.length;i++){
					var sFID = event.value + '/' + event.source.getValue('sID',ids[i]) + '.' + event.source.getValue('sOrgKindID',ids[i]);
					event.source.setValue('sFID',sFID,ids[i]);
				}
			}

			
		}
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataOrgBeforeNew = function(event) {
			
		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataOrgAfterNew = function(event){
//			event.source.setValue('sCreatorFID', event.data.person.userId, event.id);	
//			event.source.setValue('cUsercode', event.data.person.cUsercode, event.id);	
//			event.source.setValue('cUsername', event.data.person.cUsername, event.id);	
			
			//整合自身全路径编码
			var sID = event.id;
			//此处需要首先处理sID=云ID
//			var index = event.source.getIndex(sID);
//			var row = event.source.rows[index];
//			sID = event.data.person.userId;//$rootScope.getCurrentsCreatorFID();
//			row.sID.value = sID;
//			event.source.setCurrentID(sID);

			var sParent = event.source.getValue('sParent',sID);
			var sOrgKindID = event.source.getValue('sOrgKindID',sID);
			var sFID = '';
			if(sParent==null){
				sFID = '/' + sID + '.' + sOrgKindID;
			}else{
				sFID = event.source.getValue('sFID',sParent) + '/' + sID + '.' + sOrgKindID;
				//展开父节点
				$scope.dataOrg.expandRow(sParent);
			}
			event.source.setValue('sFID',sFID,sID);
			event.source.setValue('sCode', (new Date()).valueOf().toString(),sID);
			
		}

		Model.dataOrgAfterSave = function(event){
//			console.log('save.event-->',event);
			
			var rowID = event.source.getCurrentID();
			//返回列表页面（存在一个问题，就是公司信息无法刷新）
			
			var to = '/backcenter/home/center';
			var params = {};
			
//			var to = '/backcenter/ogn/list';
//			var params = {
//					"id":rowID
//					,"recordState":"none"
//					,"name":event.source.getValue('sName',rowID)
//					};
			//options：object，可选配置对象。有 location(是否更新地址栏的url，或以什么字符串替换url)，inherit(是否继承当前url的参数)，relative(当变化相对路径：如"^,定义的状态是相对的)，notify(是否广播$stateChangeStart和$stateChangeSuccess事件)，reload(是否重新载入)。
			var options = {"reload":true};
			$state.go(to,params,options);
			
			
			/*
			alert('公司信息已修改，需要注销后重新登录才生效！');
			window.location.href='/logout';
			*/
			
		}

		Model.dataOrgAfterRefresh = function(event){
			$scope.dataOrg.editData();
		}
		
		
		var options = {};
		options.container = Model;
		options.concept = 'SaOporg';
		options.name = 'dataOrg';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/backcenter/org/tree/create';
		options.reader = '/backcenter/org/tree/query';
		options.writer = '/backcenter/org/tree/save';
		options.deleter = '/backcenter/org/tree/delete';
		options.idColumnDefine = "sID";
		options.idColumnName = "sID";
		//options.defCols = {sID:{name:"sID",type:"String",label:""},sName:{name:"sName",type:"String",label:""},sCode:{name:"sCode",type:"String",label:""},sLongName:{name:"sLongName",type:"String",label:""},sFName:{name:"sFName",type:"String",label:""},sFCode:{name:"sFCode",type:"String",label:""},sFID:{name:"sFID",type:"String",label:""},sOrgKindID:{name:"sOrgKindID",type:"String",label:""},sSequence:{name:"sSequence",type:"String",label:""},sValidState:{name:"sValidState",type:"Integer",label:""},sParent:{name:"sParent",type:"String",label:""},sNodeKind:{name:"sNodeKind",type:"String",label:""},sLevel:{name:"sLevel",type:"Integer",label:""},sAddress:{name:"sAddress",type:"String",label:""},sAddressDetail:{name:"sAddressDetail",type:"String",label:""},contacts:{name:"contacts",type:"String",label:""},sPhone:{name:"sPhone",type:"String",label:""},sFax:{name:"sFax",type:"String",label:""},sMail:{name:"sMail",type:"String",label:""},sZip:{name:"sZip",type:"String",label:""},sDescription:{name:"sDescription",type:"String",label:""},sPersonID:{name:"sPersonID",type:"String",label:""},sCreatorFID:{name:"sCreatorFID",type:"String",label:""},images:{name:"images",type:"String",label:""},summary:{name:"summary",type:"String",label:""},appUrl:{name:"appUrl",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
		options.isTree = false;
		options.parentRelation = 'sParent';
		options.nodeKindRelation = 'sNodeKind';
		options.nodeLevelRelation = 'sLevel';
		options.nodeSortRelation = "sSequence";
		options.pathRelation = 'sFID';
		options.directDeleteMode = false;
   		options.limit = -1;
		options.orderBy = 'sSequence ASC';
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataOrgIndexChanged;
		options.onBeforeNew = Model.dataOrgBeforeNew;
		options.onAfterNew = Model.dataOrgAfterNew;
		options.onBeforeDelete = Model.dataOrgBeforeDelete;
		options.onAfterDelete = Model.dataOrgAfterDelete;
		options.onValueChanged = Model.dataOrgValueChanged;
		options.onDataChanged = Model.dataOrgDataChanged;
		options.onAfterSave = Model.dataOrgAfterSave;
		options.onAfterRefresh = Model.dataOrgAfterRefresh;
		
		$scope.dataOrg = new BizData(options);

		//监视对象中的所有变动
		$scope.dataOrg.deregRows = $scope.$watch('dataOrg.rows',$scope.dataOrg.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		//接收调用对话框的参数
//		console.log('$stateParams-->',$stateParams);
//        Model.title = title;  
        Model.params = $stateParams;  

		if(Model.params.recordState=='new'){
			$scope.dataOrg.loadData('');
//			var options = {};
//			$scope.dataOrg.newData(options);
			//树形专用
			var sNodeKind = 'nkLeaf';
			var sParent = null;
			var sFID = null;
			var sLevel = 1;
			var sSequence = null;
			var sValidState = 1;
			var sOrgKindID = 'ogn'
			
			sParent = null;
			sFID = null;
			sLevel = 1;
			var rootCount = $scope.dataOrg.getRoots().length;
			sSequence = '/' + common.preZeroFill(rootCount + 1,3);
			
			var options = {
					index : $scope.dataOrg.rows.length,
					defaultValues : [
					                 {
					                	 sParent:sParent
					                	 ,sNodeKind:sNodeKind
					                	 ,sLevel:sLevel
					                	 ,sSequence:sSequence
					                	 ,sValidState:sValidState
					                	 ,sOrgKindID:sOrgKindID
						            	 ,sCreatorFID: ':getCurrentPersonID()'
						            	 ,version:0
					                	 }
//					                 ,{sName:'a2',sCode:'b2'}
					                 ]
			};    

			var ids = $scope.dataOrg.newData(options);

		}
		
		if(Model.params.recordState=='edit'){
			$scope.dataOrg.id = Model.params.id;
		    $scope.dataOrg.refreshData();
		}
		
		Model.save = function() {
			$scope.dataOrg.saveData();
			
		}

		
		
		//打开对话框（选择地址）
		Model.triggerRegionCodeClick = function(){
			
     		var dataOrg = $scope.dataOrg;
     		var rowID = dataOrg.getCurrentID();
     		var sAddress = dataOrg.getValue('sAddress', rowID);
     		if(sAddress!=null && sAddress!=''){
         		dataOrg.setValue('sAddress', null, rowID);
     			return;
     		}
			

			var options = {};
	        
	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/selectRegion/selectSingle',  
	            controller: 'regionInfoSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/selectRegion/selectSingle.js')
		        }
	        });  

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
	             		//alert(returnData[i].rowid+'-->'+returnData[i].billTypeName);

	             		dataOrg.setValue('sAddress', returnData[i].regionFullName, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
  
	    ///////////////////////////页面级////////////////////////////////////////
		//返回
		Model.goBack = function(event) {
			window.history.go(-1);
		}
	    ///////////////////////////页面级////////////////////////////////////////
	    
	    //富文本编辑器
        ///////////////////////////////////////////////////////////////////////////////
		// 富文本编辑器 
		//使用：config="editorConfig"
		
		$scope.editorConfig = {
		    height: 110,
		    toolbar: [
		      // [groupName, [list of button]]
		      ['style', ['bold', 'underline', 'clear']],
		      ['color', ['color']],
		      ['para', ['ul', 'ol', 'paragraph']],
		    ],
		    dialogsInBody: true,
		    dialogsFade: true,
		};
		
		$scope.init = function() { console.log('Summernote is launched'); };
        $scope.enter = function() { console.log('Enter/Return key pressed'); };
        $scope.focus = function(e) { console.log('Editable area is focused'); };
        $scope.blur = function(e) { console.log('Editable area loses focus'); };
        $scope.paste = function(e) {
          console.log('Called event paste: ' +  e.originalEvent.clipboardData.getData('text'));
        };
        $scope.change = function(contents) {
          console.log('contents are changed:', contents, $scope.editable);
        };
        $scope.keyup = function(e) { console.log('Key is released:', e.keyCode); };
        $scope.keydown = function(e) { console.log('Key is pressed:', e.keyCode); };
//        $scope.imageUpload = function(files) {
//          console.log('image upload:', files);
//          console.log('image upload\'s editor:', $scope.editor);
//          console.log('image upload\'s editable:', $scope.editable);
//        };

        
        //上传图片
	    $scope.imageUpload = function(files) {
        	/*
            var timestamp = new Date().getTime();
            var data = new FormData();
            data.append("file", files[0]);
            data.append("key", timestamp);
            data.append("token", $scope.uptoken);
            $.ajax({
                data: data,
                type: "POST",
                //url: "http://upload.qiniu.com111",
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                	console.log('imageUpload.data-->>',data);
                    var editor = $.summernote.eventHandler.getModule();
                    editor.insertImage($scope.editable,$scope.prefix+'/'+data.key);
                },
                error: function () {
                    alert('上传失败')
                }
            });
            */
        	
            var editor = $scope.editor;
            //console.log('image upload:', files);
            //console.log('image upload\'s editor:', $scope.editor);
            //console.log('image upload\'s editable:', $scope.editable);
            var fWidth = 0;
            var fHeight = 0;

            var timestamp = new Date().getTime();
            var data = new FormData();
            data.append("file", files[0]);
            data.append("key", timestamp);
            //data.append("token", $scope.uptoken);
            
            //console.log('data-->',data);
            data.append("lastModified", files[0].lastModified);
            data.append("fileScale", fWidth+'X'+fHeight);
            data.append("destDir", "");

            $.ajax({
                data: data,
                type: "POST",
                //url: "http://upload.qiniu.com111",
                url: $rootScope.getProjectName() + '/backcenter/fastdfsFiles/list/upload', //配置的上传图片的路由
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                	console.log('imageUpload.data-->>',data);
                	if(data.code==0){
                    	var url = data.data.serverName + "/" + data.data.groupName + "/" + data.data.remoteFileName;
                        //var editor = $.summernote.eventHandler.getModule();
                    	//editor.insertImage($scope.editable ,url, data.originalFilename);
                    	
                    	$scope.editor.summernote('insertImage', url/*, data.originalFilename*/);
                    	/*
                    	$scope.editor.summernote('insertImage', url, function ($image) {
                    		  $image.css('width', $image.width() / 3);
                    		  $image.attr('data-filename', 'retriever');
                    		});
                    	*/
                	}else{
                		alert('上传失败！');
                	}
                }
            });
            
        };
        
        //图片删除
        $scope.mediaDelete = function (target){
        	console.log('target-->>',target);
            var src = target.attrs.src;
         	console.log('src-->>',src);
//          httpService.formPost("file/deleteEditorImageBySRC",{src:src})
//              .success(function(data){
//          });

            $.ajax({
                type: "POST",
                url: $rootScope.getProjectName() + '/backcenter/fastdfsFiles/list/deleteBySrc', 
                data: JSON.stringify({"src":src}),
	            contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                	console.log('mediaDelete.data-->>',data);
                	if(data.code==0){
                		alert('删除成功');
                	}else{
                		alert('删除失败');
                	}
                	
                }
            });

         };
       
        //预览功能
        $scope.preview = function (editItem) {
            ngDialog.open({
                width: 1000,
                template: 'articleDetail',
                className: 'ngdialog-theme-default',
                scope: $scope,
                controller:['$scope','$sce', function ($dlgScope,$sce) {
                    $dlgScope.previewItem = editItem;
                    $scope.trustArticleContent = $sce.trustAsHtml(editItem.content);
                      }]
                  });
              };
        ///////////////////////////////////////////////////////////////////////////////
         

		  
		return Model;
		
	}	
	
});
